package com.piece.module.flowable.handler;

import com.piece.admin.api.dto.SysUserDTO;
import com.piece.core.framework.support.convert.Convert;
import com.piece.core.framework.util.object.ObjectUtil;
import com.piece.module.flowable.constants.ProcessConstants;
import com.piece.module.flowable.util.UserTaskUtil;
import lombok.AllArgsConstructor;
import org.flowable.bpmn.model.FlowElement;
import org.flowable.bpmn.model.UserTask;
import org.flowable.engine.delegate.DelegateExecution;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;

/**
 * 多实例处理类
 */
@AllArgsConstructor
@Component("multiInstanceHandler")
public class MultiInstanceHandler {

    public HashSet<String> multiAssignee(DelegateExecution execution) {
        HashSet<String> candidateUserIds = new LinkedHashSet<>();
        FlowElement flowElement = execution.getCurrentFlowElement();
        if (ObjectUtil.isNotEmpty(flowElement) && flowElement instanceof UserTask) {
            UserTask userTask = (UserTask) flowElement;
            String dataType = userTask.getAttributeValue(ProcessConstants.NAMESPACE, ProcessConstants.PROCESS_CUSTOM_DATA_TYPE);
            List<SysUserDTO> userList = UserTaskUtil.getFlowCandidate(userTask, dataType);
            userList.stream().forEach(user -> {
                candidateUserIds.add(Convert.toStr(user.getUserId(), null));
            });
        }
        return candidateUserIds;
    }
}
